package com.example.licenseappclient;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class SocketHelper {
        private Socket socket;
        private BufferedReader in ;
        private BufferedWriter out;

    public SocketHelper(String ipAddr,int port) {
        try {
            InetAddress addr = InetAddress.getByName(ipAddr);
            socket = new Socket(addr,port);
            out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void sendMessage(String message) throws IOException{
        out.write(message);
        out.flush();
        socket.shutdownOutput();
    }

    public String receiveMessage() throws IOException{
        StringBuilder res = new StringBuilder();

        String line;
        while((line=in.readLine())!=null) res.append(line);

        return res.toString();
    }

    public void close() throws IOException{
        if(out!=null) out.close();
        if(in!=null) in.close();
        if(socket!=null) socket.close();
    }
}
